<template>
  <div class="asset-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>资产管理</span>
          <div class="header-actions">
            <el-button type="success" @click="showImportDialog">
              <el-icon><Upload /></el-icon>
              批量导入
            </el-button>
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加资产
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="资产名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入资产名称"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="资产类型">
            <el-select
              v-model="searchForm.type"
              placeholder="请选择资产类型"
              clearable
              style="width: 150px"
            >
              <el-option label="服务器" value="server" />
              <el-option label="网络设备" value="network" />
              <el-option label="存储设备" value="storage" />
              <el-option label="安全设备" value="security" />
              <el-option label="软件" value="software" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="在线" value="online" />
              <el-option label="离线" value="offline" />
              <el-option label="维护中" value="maintenance" />
              <el-option label="已报废" value="scrapped" />
            </el-select>
          </el-form-item>
          <el-form-item label="所属部门">
            <el-select
              v-model="searchForm.department"
              placeholder="请选择部门"
              clearable
              style="width: 150px"
            >
              <el-option label="技术部" value="tech" />
              <el-option label="运维部" value="ops" />
              <el-option label="产品部" value="product" />
              <el-option label="市场部" value="marketing" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计卡片 -->
      <div class="stats-cards">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="stat-card total">
              <div class="stat-icon">
                <el-icon><Monitor /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.total }}</div>
                <div class="stat-label">总资产数</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card online">
              <div class="stat-icon">
                <el-icon><CircleCheck /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.online }}</div>
                <div class="stat-label">在线资产</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card offline">
              <div class="stat-icon">
                <el-icon><CircleClose /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.offline }}</div>
                <div class="stat-label">离线资产</div>
              </div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-card maintenance">
              <div class="stat-icon">
                <el-icon><Tools /></el-icon>
              </div>
              <div class="stat-content">
                <div class="stat-number">{{ stats.maintenance }}</div>
                <div class="stat-label">维护中</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 资产表格 -->
      <el-table
        :data="assetList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="资产ID" width="100" />
        <el-table-column prop="name" label="资产名称" min-width="150" />
        <el-table-column prop="type" label="资产类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getTypeTagType(row.type)">
              {{ getTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="department" label="所属部门" width="120" />
        <el-table-column prop="owner" label="负责人" width="100" />
        <el-table-column prop="location" label="位置" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑资产对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="800px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="资产名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入资产名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择资产类型" style="width: 100%">
                <el-option label="服务器" value="server" />
                <el-option label="网络设备" value="network" />
                <el-option label="存储设备" value="storage" />
                <el-option label="安全设备" value="security" />
                <el-option label="软件" value="software" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="IP地址" prop="ip">
              <el-input v-model="form.ip" placeholder="请输入IP地址" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="在线" value="online" />
                <el-option label="离线" value="offline" />
                <el-option label="维护中" value="maintenance" />
                <el-option label="已报废" value="scrapped" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="所属部门" prop="department">
              <el-select v-model="form.department" placeholder="请选择部门" style="width: 100%">
                <el-option label="技术部" value="tech" />
                <el-option label="运维部" value="ops" />
                <el-option label="产品部" value="product" />
                <el-option label="市场部" value="marketing" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="owner">
              <el-input v-model="form.owner" placeholder="请输入负责人" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="位置" prop="location">
              <el-input v-model="form.location" placeholder="请输入位置" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="序列号" prop="serialNumber">
              <el-input v-model="form.serialNumber" placeholder="请输入序列号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入资产描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Upload,
  Search,
  Monitor,
  CircleCheck,
  CircleClose,
  Tools
} from '@element-plus/icons-vue'

// 注册图标组件
const iconComponents = {
  Plus,
  Upload,
  Search,
  Monitor,
  CircleCheck,
  CircleClose,
  Tools
}

// 路由
const router = useRouter()

// 接口定义
interface Asset {
  id: string
  name: string
  type: string
  ip: string
  status: string
  department: string
  owner: string
  location: string
  serialNumber: string
  description: string
  createTime: string
}

interface SearchForm {
  name: string
  type: string
  status: string
  department: string
}

interface Stats {
  total: number
  online: number
  offline: number
  maintenance: number
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加资产')
const isEdit = ref(false)
const selectedAssets = ref<Asset[]>([])

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  type: '',
  status: '',
  department: ''
})

// 统计数据
const stats = reactive<Stats>({
  total: 0,
  online: 0,
  offline: 0,
  maintenance: 0
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 资产列表
const assetList = ref<Asset[]>([])

// 表单数据
const form = reactive<Asset>({
  id: '',
  name: '',
  type: '',
  ip: '',
  status: '',
  department: '',
  owner: '',
  location: '',
  serialNumber: '',
  description: '',
  createTime: ''
})

// 表单引用
const formRef = ref()

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入资产名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择资产类型', trigger: 'change' }
  ],
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    {
      pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      message: '请输入正确的IP地址格式',
      trigger: 'blur'
    }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  department: [
    { required: true, message: '请选择所属部门', trigger: 'change' }
  ],
  owner: [
    { required: true, message: '请输入负责人', trigger: 'blur' }
  ]
}

// 获取资产类型标签类型
const getTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    server: 'primary',
    network: 'success',
    storage: 'warning',
    security: 'danger',
    software: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取资产类型标签文本
const getTypeLabel = (type: string) => {
  const typeMap: Record<string, string> = {
    server: '服务器',
    network: '网络设备',
    storage: '存储设备',
    security: '安全设备',
    software: '软件'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    online: 'success',
    offline: 'danger',
    maintenance: 'warning',
    scrapped: 'info'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中',
    scrapped: '已报废'
  }
  return statusMap[status] || status
}

// 获取资产列表
const getAssetList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 模拟数据
    const mockData: Asset[] = [
      {
        id: 'ASSET001',
        name: 'Web服务器-01',
        type: 'server',
        ip: '192.168.1.100',
        status: 'online',
        department: 'tech',
        owner: '张三',
        location: '机房A-01',
        serialNumber: 'SN001234567',
        description: '主要用于Web应用部署',
        createTime: '2024-01-15 10:30:00'
      },
      {
        id: 'ASSET002',
        name: '核心交换机',
        type: 'network',
        ip: '192.168.1.1',
        status: 'online',
        department: 'ops',
        owner: '李四',
        location: '机房A-02',
        serialNumber: 'SN001234568',
        description: '核心网络交换设备',
        createTime: '2024-01-16 14:20:00'
      },
      {
        id: 'ASSET003',
        name: '存储阵列-01',
        type: 'storage',
        ip: '192.168.1.200',
        status: 'maintenance',
        department: 'ops',
        owner: '王五',
        location: '机房B-01',
        serialNumber: 'SN001234569',
        description: '主要存储设备',
        createTime: '2024-01-17 09:15:00'
      },
      {
        id: 'ASSET004',
        name: '防火墙设备',
        type: 'security',
        ip: '192.168.1.254',
        status: 'online',
        department: 'ops',
        owner: '赵六',
        location: '机房A-03',
        serialNumber: 'SN001234570',
        description: '网络安全防护设备',
        createTime: '2024-01-18 16:45:00'
      },
      {
        id: 'ASSET005',
        name: '数据库服务器',
        type: 'server',
        ip: '192.168.1.101',
        status: 'offline',
        department: 'tech',
        owner: '孙七',
        location: '机房A-04',
        serialNumber: 'SN001234571',
        description: '数据库服务器',
        createTime: '2024-01-19 11:30:00'
      }
    ]

    assetList.value = mockData
    pagination.total = mockData.length

    // 更新统计数据
    stats.total = mockData.length
    stats.online = mockData.filter(item => item.status === 'online').length
    stats.offline = mockData.filter(item => item.status === 'offline').length
    stats.maintenance = mockData.filter(item => item.status === 'maintenance').length

  } catch (error) {
    ElMessage.error('获取资产列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getAssetList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    type: '',
    status: '',
    department: ''
  })
  handleSearch()
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加资产'
  isEdit.value = false
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: Asset) => {
  dialogTitle.value = '编辑资产'
  isEdit.value = true
  Object.assign(form, row)
  dialogVisible.value = true
}

// 显示详情页面
const showDetailDialog = (row: Asset) => {
  // 跳转到资产详情页面
  router.push(`/cmdb/assets/${row.id}`)
}

// 显示导入对话框
const showImportDialog = () => {
  ElMessage.info('批量导入功能开发中...')
}

// 删除资产
const handleDelete = (row: Asset) => {
  ElMessageBox.confirm(
    `确定要删除资产 "${row.name}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟删除操作
    const index = assetList.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      assetList.value.splice(index, 1)
      pagination.total--
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 表格选择变化
const handleSelectionChange = (selection: Asset[]) => {
  selectedAssets.value = selection
}

// 提交表单
const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑逻辑
        const index = assetList.value.findIndex(item => item.id === form.id)
        if (index > -1) {
          assetList.value[index] = { ...form }
          ElMessage.success('编辑成功')
        }
      } else {
        // 添加逻辑
        const newAsset: Asset = {
          ...form,
          id: `ASSET${String(Date.now()).slice(-6)}`,
          createTime: new Date().toLocaleString()
        }
        assetList.value.unshift(newAsset)
        pagination.total++
        ElMessage.success('添加成功')
      }
      dialogVisible.value = false
      resetForm()
    }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: '',
    name: '',
    type: '',
    ip: '',
    status: '',
    department: '',
    owner: '',
    location: '',
    serialNumber: '',
    description: '',
    createTime: ''
  })
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  getAssetList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  getAssetList()
}

// 组件挂载时获取数据
onMounted(() => {
  getAssetList()
})
</script>

<style scoped>
.asset-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(120, 220, 255, 0.1);
}

.search-form {
  margin: 0;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  background: rgba(255, 255, 255, 0.03);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(120, 220, 255, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(120, 220, 255, 0.15);
}

.stat-card.total {
  border-color: rgba(64, 158, 255, 0.3);
}

.stat-card.online {
  border-color: rgba(103, 194, 58, 0.3);
}

.stat-card.offline {
  border-color: rgba(245, 108, 108, 0.3);
}

.stat-card.maintenance {
  border-color: rgba(230, 162, 60, 0.3);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
}

.total .stat-icon {
  background: linear-gradient(135deg, rgba(64, 158, 255, 0.2), rgba(64, 158, 255, 0.1));
  color: #409eff;
}

.online .stat-icon {
  background: linear-gradient(135deg, rgba(103, 194, 58, 0.2), rgba(103, 194, 58, 0.1));
  color: #67c23a;
}

.offline .stat-icon {
  background: linear-gradient(135deg, rgba(245, 108, 108, 0.2), rgba(245, 108, 108, 0.1));
  color: #f56c6c;
}

.maintenance .stat-icon {
  background: linear-gradient(135deg, rgba(230, 162, 60, 0.2), rgba(230, 162, 60, 0.1));
  color: #e6a23c;
}

.stat-content {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  color: var(--tech-accent-color);
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: var(--tech-text-secondary);
  opacity: 0.8;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 表格样式优化 */
:deep(.el-table) {
  background: rgba(255, 255, 255, 0.02);
  border: 1px solid rgba(120, 220, 255, 0.1);
}

:deep(.el-table__header) {
  background: rgba(120, 220, 255, 0.05);
}

:deep(.el-table th) {
  background: rgba(120, 220, 255, 0.05);
  border-color: rgba(120, 220, 255, 0.1);
  color: var(--tech-text-primary);
}

:deep(.el-table td) {
  border-color: rgba(120, 220, 255, 0.1);
  color: var(--tech-text-secondary);
}

:deep(.el-table__row:hover) {
  background: rgba(120, 220, 255, 0.05);
}

/* 对话框样式 */
:deep(.el-dialog) {
  background: rgba(15, 25, 40, 0.95);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(120, 220, 255, 0.2);
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid rgba(120, 220, 255, 0.1);
  padding-bottom: 15px;
}

:deep(.el-dialog__title) {
  color: var(--tech-text-primary);
  font-weight: 600;
}
</style>
